import QtQuick 2.0
import QtLocation 5.3
import QtQuick.Controls 1.2
import QtQuick.Window 2.0
import "../../javascript/Utils.js" as UtilsJS

Map {
    id: map
    zoomLevel: (maximumZoomLevel - minimumZoomLevel)/2
    plugin: Plugin {
        id: mapPlugin
        name: "osm"
    }

    center {
        latitude: -27.5796
        longitude: 153.1003
    }

    gesture.flickDeceleration: 3000
    gesture.enabled: true

    property variant userMarker: null
    property variant markers
    property int markerCounter: 0

    signal resetState()
    signal markerClicked(string id, string label)

    property int lastX : -1
    property int lastY : -1
    property int pressX : -1
    property int pressY : -1
    property int jitterThreshold : 30
    property variant scaleLengths: [5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000, 100000, 200000, 500000, 1000000, 2000000]

    Component.onCompleted: {
        markers = new Array();
        zoomLevel = ((maximumZoomLevel + minimumZoomLevel) * 85 / 100)
        console.log("Max:"+maximumZoomLevel+" Min:"+minimumZoomLevel+" L:"+zoomLevel);
    }

    Slider {
        id: zoomSlider;
        minimumValue: map.minimumZoomLevel;
        maximumValue: map.maximumZoomLevel;
        opacity: 1
        visible: parent.visible
        z: map.z + 3
        anchors {
            bottom: parent.bottom;
            bottomMargin: 15; rightMargin: 10; leftMargin: 90
            left: parent.left
        }
        width: parent.width - anchors.rightMargin - anchors.leftMargin

        value: map.zoomLevel

        Binding {
            target: zoomSlider; property: "value"; value: map.zoomLevel
        }

        onValueChanged: {
            map.zoomLevel = value
            map.state=""
            map.resetState()
        }
    }

    Item {//scale
        id: scale
        parent: zoomSlider.parent
        visible: scaleText.text != "0 m"
        z: map.z + 2
        opacity: 0.6
        anchors {
            bottom: zoomSlider.top;
            bottomMargin: 8;
            left: zoomSlider.left
        }
        Image {
            id: scaleImageLeft
            source: "qrc:/images/scale_end.png"
            anchors.bottom: parent.bottom
            anchors.left: parent.left
        }
        Image {
            id: scaleImage
            source: "qrc:/images/scale.png"
            anchors.bottom: parent.bottom
            anchors.left: scaleImageLeft.right
        }
        Image {
            id: scaleImageRight
            source: "qrc:/images/scale_end.png"
            anchors.bottom: parent.bottom
            anchors.left: scaleImage.right
        }
        Text {
            id: scaleText
            color: "#004EAE"
            horizontalAlignment: Text.AlignHCenter
            anchors.bottom: parent.bottom
            anchors.left: parent.left
            anchors.bottomMargin: 3
            text: "0 m"
            font.pixelSize: 14
        }
        Component.onCompleted: {
            map.calculateScale();
        }
    }

    Timer {
        id: scaleTimer
        interval: 100
        running: false
        repeat: false
        onTriggered: {
            map.calculateScale();
        }
    }

    onCenterChanged:{
        scaleTimer.restart();
    }

    onZoomLevelChanged:{
        scaleTimer.restart();
    }

    onWidthChanged:{
        scaleTimer.restart();
    }

    onHeightChanged:{
        scaleTimer.restart();
    }

    MouseArea {
        id: mouseArea
        property variant lastCoordinate
        anchors.fill: parent

        onPressed : {
            map.resetState();
            map.state = "";
            map.lastX = mouse.x;
            map.lastY = mouse.y;
            map.pressX = mouse.x;
            map.pressY = mouse.y;
            lastCoordinate = map.toCoordinate(Qt.point(mouse.x, mouse.y));
        }

        onPositionChanged: {
            if (map.state != "PopupMenu" ||
                Math.abs(map.pressX - mouse.x ) > map.jitterThreshold ||
                Math.abs(map.pressY - mouse.y ) > map.jitterThreshold) {
                map.state = "";
            }
            if ((mouse.button == Qt.LeftButton) & (map.state == "")) {
                map.lastX = mouse.x;
                map.lastY = mouse.y;
            }
        }

        onDoubleClicked: {
            map.center = map.toCoordinate(Qt.point(mouse.x, mouse.y))
            if (mouse.button == Qt.LeftButton){
                map.zoomLevel += 1;
            } else if (mouse.button == Qt.RightButton)
                map.zoomLevel -= 1;
            lastX = -1;
            lastY = -1;
        }

    }

    function calculateScale() {
        var coord1, coord2, dist, text, f;
        f = 0;
        coord1 = map.toCoordinate(Qt.point(0,scale.y));
        coord2 = map.toCoordinate(Qt.point(0+scaleImage.sourceSize.width,scale.y));
        dist = Math.round(coord1.distanceTo(coord2));

        if (dist === 0) {
            // not visible
        } else {
            for (var i = 0; i < scaleLengths.length-1; i++) {
                if (dist < (scaleLengths[i] + scaleLengths[i+1]) / 2 ) {
                    f = scaleLengths[i] / dist;
                    dist = scaleLengths[i];
                    break;
                }
            }
            if (f === 0) {
                f = dist / scaleLengths[i];
                dist = scaleLengths[i];
            }
        }

        text = formatDistance(dist);
        scaleImage.width = (scaleImage.sourceSize.width * f) - 2 * scaleImageLeft.sourceSize.width;
        scaleText.text = text;
    }


    function formatDistance(meters)
    {
        var dist = Math.round(meters);
        if (dist > 1000 ){
            if (dist > 100000){
                dist = Math.round(dist / 1000);
            }
            else{
                dist = Math.round(dist / 100);
                dist = dist / 10;
            }
            dist = dist + " km";
        }
        else{
            dist = dist + " m";
        }
        return dist;
    }

    function setLanguage(lang) {
        map.plugin.locales = lang;
        if (map.plugin.locales.length  >  0) {
            languageButton.text = map.plugin.locales[0];
        }
    }


    function onMapMarkerClicked(idFornecedor, label) {
        markerClicked(idFornecedor, label);
    }

    function deleteMarkers() {
        var count = map.markers.length;
        for (var i = 0; i<count; i++) {
            map.removeMapItem(map.markers[i]);
            map.markers[i].destroy();
        }
        map.markers = [];
        markerCounter = 0;

        if(map.userMarker!=null) {
            map.removeMapItem(map.userMarker);
            map.userMarker.destroy();
            map.userMarker = null;
        }
    }

    function addMarker(id, lat , lon, label, color) {
        var count = map.markers.length;
        var image = "qrc:/images/marker_"+color+".png";

        markerCounter++;
        var marker = Qt.createQmlObject ('Marker {}', map);

        marker.idFornecedor = id;
        marker.label = label;
        marker.image = image;

        map.addMapItem(marker);
        marker.z = map.z+1
        marker.coordinate.latitude = lat;
        marker.coordinate.longitude = lon;

        marker.clicked.connect(onMapMarkerClicked);

        //update list of markers
        var myArray = new Array();
        for (var i = 0; i<count; i++){
            myArray.push(markers[i]);
        }
        myArray.push(marker);
        markers = myArray;

        return marker;
    }

    function addMarkers(estabelecimentos) {
        var i;
        for(i=0; i<estabelecimentos.length; i++) {
            addMarker(estabelecimentos[i]["id"],estabelecimentos[i]["lat"],estabelecimentos[i]["lon"],
                      estabelecimentos[i]["nome"],estabelecimentos[i]["color"]);
        }
    }

    function setCenter(lat, lon) {
        map.center.latitude = lat;
        map.center.longitude = lon;
        if(map.userMarker==null) {
            map.userMarker=addMarker(-1,lat,lon,"Usuario","blue");
        } else {
            map.userMarker.coordinate.latitude = lat;
            map.userMarker.coordinate.longitude = lon;
        }
    }
}
